package com.example.common.mvvm.view;

import android.os.Bundle;
import android.view.LayoutInflater;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewbinding.ViewBinding;

import com.example.common.mvvm.viewmodel.BaseViewModel;

import java.lang.reflect.ParameterizedType;

public abstract class BaseActivity<V extends ViewBinding,VM extends BaseViewModel> extends AppCompatActivity implements IView{

    protected LayoutInflater inflater;
    protected V v;
    protected VM vm;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        inflater = LayoutInflater.from(this);
        v = (V) initBinding();
        setContentView(bindLayout());
        initViewModel();
        getLifecycle().addObserver(vm);
        initView();
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getLifecycle().removeObserver(vm);
    }

    @Override
    public void initViewModel() {
        ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
        Class clazz = (Class) type.getActualTypeArguments()[1];
        vm = (VM) new ViewModelProvider(this,new ViewModelProvider.NewInstanceFactory())
                .get(clazz);
    }
}
